<!--
 * @Description:
 * @version:
 * @Author: 尹鹏孝
 * @Date: 2023-03-10 14:44:43
 * @LastEditors: 尹鹏孝
 * @LastEditTime: 2023-03-10 15:27:56
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发布订阅模式</title>
</head>
<body>
    <script>
        const eventHub=()=>({
            hub:Object.create(null),
            pub(event, data){
               (this.hub[event] || []).forEach(handler=>handler(data))
            },
            sub(event,handler){
                if(!this.hub[event]){
                     this.hub[event]=[];
                }
                this.hub[event].push(handler);

            },
            off(event, handler){
                let index = this.hub[event].indexOf(handler)
                index>-1&& this.hub[event].splice(index,1)
            }
        })

        const eventHubTest= eventHub();
        const handle = data => {
                console.log(data);
            }

            eventHubTest.sub('myEvent', handle);
            eventHubTest.sub('myEvent', () => {
                console.log('handle2')
            });
            eventHubTest.sub('myEvent2', () => {
                console.log('eventHub', eventHubTest);
            });

            eventHubTest.pub('myEvent', 'a string !!!');
            eventHubTest.pub('myEvent', { arg: 'a object!!!' });
            eventHubTest.pub('myEvent2');

            eventHubTest.off('myEvent', handle);
    </script>
</body>
</html>